using System.IO.IsolatedStorage;
using KlearTweet.Client.Model;

namespace KlearTweet.Client.Storage
{
    public static class Database
    {
        public static System.Collections.Generic.IList<Account> LoadAccounts()
        {
            var list = new System.Collections.Generic.List<Account>();

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists("KlearTweetAccounts"))
                    using (var reader = new System.IO.StreamReader(store.OpenFile("KlearTweetAccounts", System.IO.FileMode.Open)))
                    {
                        while (!reader.EndOfStream)
                        {
                            var accountString = reader.ReadLine();
                            var parts = accountString.Split('\t');

                            var account = new Account
                            {
                                User = new User { UserName = parts[0] },
                                AuthToken = parts[1],
                                ApplicationConsumerKey = parts[2],
                            };
                            list.Add(account);
                        }
                    }
            }

            return list;
        }


        public static void Save(System.Collections.Generic.IList<Account> list)
        {
            var sb = new System.Text.StringBuilder();
            foreach (var e in list)
                sb.AppendLine(e.User.UserName + '\t' + e.AuthToken + '\t' + e.ApplicationConsumerKey);

            if (sb.Length == 0)
                return;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var writer = new System.IO.StreamWriter(store.CreateFile("KlearTweetAccounts")))
                writer.Write(sb.ToString());
        }


        public static string LoadParameter(string paramName)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var reader = new System.IO.StreamReader(store.OpenFile("KlearTweet." + paramName, System.IO.FileMode.Open)))
                {
                    var paramValue = reader.ReadToEnd();
                    return paramValue;
                }
            }
        }


        public static void SaveParameter(string paramName, string paramValue)
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var writer = new System.IO.StreamWriter(store.CreateFile("KlearTweet." + paramName)))
                writer.Write(paramValue);
        }
    }
}